namespace taurus.client{

    /**
     * EventDispatcher 事件派发器类，负责进行事件的发送和侦听。
     */
    export class EventDispatcher{

        private listenersByEvent:any;

        public constructor(){
            this.listenersByEvent = {};
        }

        /**
         * 添加指定类型的事件监听
         * @param eventName
         * @param listener
         */
        public addEventListener(eventName:string, listener:Function,thisObject:any){
            var listeners:any[] = this.listenersByEvent[eventName];
            if (listeners == null) {
                listeners = [];
                this.listenersByEvent[eventName] = listeners;
            }
            listeners.push({
                listener:listener,thisObject: thisObject
            });
        }
        
        /**
         * 删除指定的事件监听
         * @param eventName
         * @param listener
         */
        public removeEventListener(eventName:string, listener:Function, thisObject:any){
            var listeners:any[]  = this.listenersByEvent[eventName];
            if (listeners){
                for (var i = 0; i < listeners.length; i++) {
                    var tem = listeners[i];
                    if (tem.listener === listener && tem.thisObject == thisObject) {
                        listeners.splice(i, 1);
                        break;
                    }
                }
            }
        }
        
        /**
         * 删除所有的事件监听
         */
        public removeAllListener(){
            this.listenersByEvent = {}
        }
        
        /**
         * 
         * @param event
         */
        public dispatchEvent(event:Event){
            var listeners:any[]  = this.listenersByEvent[event.name];
            if (listeners){
                for (var i = 0; i < listeners.length; i++) {
                    var tem = listeners[i];
                    tem.listener.call(tem.thisObject,event);
                }
            }
        }
    }
}